package io.github.heollhai.common.config.api;

import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.*;
import java.util.stream.Collectors;

@Component
@Slf4j
public class ApiScanner {

    private static final String BASE_PACKAGE = "com.mf.controller"; // 指定Controller所在的包名

    @Resource
    private ApplicationContext context;

    /**
     * 将模板{}中的内容替换成 *
     */
    public String replacePathVariable(String path) {
        return path.replaceAll("\\{\\w+\\}", "*");
    }

    public List<Map<String,String>> findAllApis() {
        RequestMappingHandlerMapping mapping = context.getBean(RequestMappingHandlerMapping.class);

        Map<RequestMappingInfo, HandlerMethod> handlerMethods = mapping.getHandlerMethods();
        ArrayList<Map<String,String>> arrayList = new ArrayList<>();

        handlerMethods.entrySet().stream()
                .filter(entry -> entry.getValue().getBeanType().getName().startsWith(BASE_PACKAGE))
                .forEach(entry -> {
                    Map<String, String> map = new HashMap<>();
                    Set<String> patternValues = entry.getKey().getPatternValues();
                    List<String> paths = new ArrayList<>(patternValues);
                    if (!paths.isEmpty()) {
                        String path = paths.get(0); // 这里假设我们只取第一个路径（实际可能需要处理多个路径）

                        // 查找类级别的@Tag注解
                        Tag tag = entry.getValue().getBeanType().getAnnotation(Tag.class);
                        RequestMapping requestMapping =
                                entry.getValue().getBeanType().getAnnotation(RequestMapping.class);

                        // 获取类级别的@Tag注解的name属性作为标签名称
                        String tagName = tag != null ? tag.name() : requestMapping != null ? requestMapping.value()[0]
                                : "";

                        // 这里可以继续检查方法级别的@Operation注解（如果需要）
                        io.swagger.v3.oas.annotations.Operation operation =
                                entry.getValue().getMethodAnnotation(io.swagger.v3.oas.annotations.Operation.class);
                        String summary = operation != null ? operation.summary() : path;
                        map.put("path", replacePathVariable(path));
                        map.put("name", tagName); // 使用类级别的@Tag注解中的name
                        map.put("summary", summary); // 可选：如果也需要方法级别的summary
                        map.put("id", summary);
                        map.put("pid",tagName);
                        map.put("sort", "0");

                        arrayList.add(map);
                    }
                });

        Set<String> names = arrayList.stream().map(api -> api.get("name")).collect(Collectors.toSet());
        for (String name : names) {
            HashMap<String, String> hashMap = new HashMap<>();
            hashMap.put("name", name);
            hashMap.put("pid", "0");
            hashMap.put("id", name);
            hashMap.put("sort", "0");
            hashMap.put("path", name);
            arrayList.add(hashMap);
        }

        return arrayList;
    }
}
